package goodenglish.domain.service.analysis;

import goodenglish.domain.model.lexicon.NewWord;
import goodenglish.domain.model.subt.SubtSentence;
import goodenglish.domain.service.impl.SubtBackServiceFile;
import goodenglish.infrastructure.Config;
import goodenglish.interfaces.UUID;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 从备份文件中字符串中恢复句子
 * 
 * @author hp
 * 
 */
public class ReBackAnalyzer extends AbsAnalyzer {
	protected String newWordStr;

	public ReBackAnalyzer(final File file) {
		super(file);
		newWordStr = subtStr.split(SubtBackServiceFile.SEPARATE)[1].trim();
		subtStr = subtStr.split(SubtBackServiceFile.SEPARATE)[0].trim();

	}

	@Override
	public String analysisSubtName() {
		return file.getName().substring(0, file.getName().length() - 17);
	}

	/**
	 * 从字幕串里分析出句子
	 * 
	 * @param subtStr
	 * @param subt
	 */
	@Override
	public List<SubtSentence> analysisSentens() {
		List<SubtSentence> sentences = new ArrayList<SubtSentence>();
		String[] strs = subtStr.split(Config.LINE_SPLITER);
		int index = 1;
		int i = 1;
		SubtSentence sentence = null;
		for (final String str : strs) {
			if (str == null || str.isEmpty()) {
				continue;
			}
			if (str.equals("" + index)) {
				sentence = new SubtSentence();
				sentences.add(sentence);
				index++;
				i = 1;
			} else {
				if (i == 1) {
					sentence.setStimeStr(str.split(Config.TIME_SPLITER)[0].trim());
					sentence.setEtimeStr(str.split(Config.TIME_SPLITER)[1].trim());

				}
				if (i == 2) {
					sentence.setStime(Integer.parseInt(str.split(Config.TIME_SPLITER)[0].trim()));
					sentence.setEtime(Integer.parseInt(str.split(Config.TIME_SPLITER)[1].trim()));
				}
				if (i == 3) {
					sentence.setEnStr(str);
				}
				if (i == 4) {
					sentence.setChStr(str);
				}
				i++;

			}

		}
		return sentences;
	}

	@Override
	public List<NewWord> analysisWords() {
		List<NewWord> subtWords = new ArrayList<NewWord>();
		String wordArray[] = newWordStr.split(Config.LINE_SPLITER);
		for (String str : wordArray) {
			String[] strArray = str.split(Config.WORD_SPLITER);
			if (strArray[0] != null && !strArray[0].trim().equals("")) {
				NewWord word = new NewWord();
				word.setId(UUID.getUUID());
				word.setSpell(strArray[0].trim());
				if (strArray.length > 1) {
					word.setExplain(strArray[1]);
				}
				subtWords.add(word);
			}

		}
		return subtWords;
	}
}
